'use client'

import { useState, useEffect } from 'react'
import { motion } from 'framer-motion'
import { BarChart3, TrendingUp, Users, BookOpen, Target, ArrowLeft } from 'lucide-react'
import Link from 'next/link'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'

interface AnalyticsData {
  userGrowth: { month: string; count: number }[]
  topicPopularity: { topic: string; sessions: number }[]
  accuracyTrend: { date: string; accuracy: number }[]
  gradeDistribution: { grade: string; count: number }[]
}

export default function AnalyticsPage() {
  const [data, setData] = useState<AnalyticsData | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [timeRange, setTimeRange] = useState('30d')

  useEffect(() => {
    loadAnalytics()
  }, [timeRange])

  const loadAnalytics = async () => {
    try {
      setIsLoading(true)
      const response = await fetch(`/api/admin/analytics?range=${timeRange}`, {
        credentials: 'include'
      })
      
      if (response.ok) {
        const result = await response.json()
        if (result.success) {
          setData(result.data)
        }
      }
    } catch (error) {
      console.error('加载分析数据错误:', error)
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50">
      {/* 导航栏 */}
      <nav className="glassmorphism border-b border-white/20">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between h-16">
            <div className="flex items-center space-x-4">
              <Link href="/admin">
                <Button variant="ghost" size="sm">
                  <ArrowLeft className="w-4 h-4 mr-2" />
                  返回管理面板
                </Button>
              </Link>
              <div className="flex items-center space-x-2">
                <BarChart3 className="w-6 h-6 text-indigo-600" />
                <span className="text-xl font-bold text-gray-800">数据分析</span>
              </div>
            </div>
            <div>
              <select
                value={timeRange}
                onChange={(e) => setTimeRange(e.target.value)}
                className="px-4 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-indigo-500"
              >
                <option value="7d">最近7天</option>
                <option value="30d">最近30天</option>
                <option value="90d">最近90天</option>
                <option value="1y">最近1年</option>
              </select>
            </div>
          </div>
        </div>
      </nav>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* 页面标题 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="mb-8"
        >
          <h1 className="text-3xl font-bold text-gray-800 mb-2">数据分析</h1>
          <p className="text-gray-600">查看系统使用情况和学习数据分析</p>
        </motion.div>

        {isLoading ? (
          <div className="flex items-center justify-center py-12">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600"></div>
          </div>
        ) : (
          <>
            {/* 关键指标 */}
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.1 }}
              className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8"
            >
              <Card className="glassmorphism">
                <CardHeader className="pb-3">
                  <CardDescription className="flex items-center gap-2">
                    <Users className="w-4 h-4" />
                    活跃用户
                  </CardDescription>
                  <CardTitle className="text-3xl text-indigo-600">342</CardTitle>
                  <p className="text-sm text-green-600 flex items-center gap-1">
                    <TrendingUp className="w-4 h-4" />
                    +12.5%
                  </p>
                </CardHeader>
              </Card>

              <Card className="glassmorphism">
                <CardHeader className="pb-3">
                  <CardDescription className="flex items-center gap-2">
                    <BookOpen className="w-4 h-4" />
                    练习次数
                  </CardDescription>
                  <CardTitle className="text-3xl text-blue-600">5,432</CardTitle>
                  <p className="text-sm text-green-600 flex items-center gap-1">
                    <TrendingUp className="w-4 h-4" />
                    +8.3%
                  </p>
                </CardHeader>
              </Card>

              <Card className="glassmorphism">
                <CardHeader className="pb-3">
                  <CardDescription className="flex items-center gap-2">
                    <Target className="w-4 h-4" />
                    平均正确率
                  </CardDescription>
                  <CardTitle className="text-3xl text-purple-600">78.5%</CardTitle>
                  <p className="text-sm text-green-600 flex items-center gap-1">
                    <TrendingUp className="w-4 h-4" />
                    +2.1%
                  </p>
                </CardHeader>
              </Card>

              <Card className="glassmorphism">
                <CardHeader className="pb-3">
                  <CardDescription className="flex items-center gap-2">
                    <BarChart3 className="w-4 h-4" />
                    学习时长
                  </CardDescription>
                  <CardTitle className="text-3xl text-green-600">1,234h</CardTitle>
                  <p className="text-sm text-green-600 flex items-center gap-1">
                    <TrendingUp className="w-4 h-4" />
                    +15.7%
                  </p>
                </CardHeader>
              </Card>
            </motion.div>

            {/* 图表区域 */}
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              {/* 用户增长趋势 */}
              <motion.div
                initial={{ opacity: 0, x: -20 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{ delay: 0.2 }}
              >
                <Card className="glassmorphism">
                  <CardHeader>
                    <CardTitle>用户增长趋势</CardTitle>
                    <CardDescription>新注册用户数量变化</CardDescription>
                  </CardHeader>
                  <CardContent>
                    <div className="h-64 flex items-center justify-center text-gray-500">
                      <div className="text-center">
                        <BarChart3 className="w-16 h-16 mx-auto mb-4 text-gray-400" />
                        <p>图表功能开发中...</p>
                        <p className="text-sm mt-2">将集成 Chart.js 或 Recharts</p>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </motion.div>

              {/* 题型热度 */}
              <motion.div
                initial={{ opacity: 0, x: 20 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{ delay: 0.3 }}
              >
                <Card className="glassmorphism">
                  <CardHeader>
                    <CardTitle>题型热度排行</CardTitle>
                    <CardDescription>最受欢迎的题型</CardDescription>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-4">
                      {[
                        { name: '鸡兔同笼', count: 1234, color: 'bg-blue-500' },
                        { name: '行程问题', count: 987, color: 'bg-purple-500' },
                        { name: '几何计算', count: 856, color: 'bg-green-500' },
                        { name: '分数应用题', count: 743, color: 'bg-yellow-500' },
                        { name: '和差倍问题', count: 621, color: 'bg-red-500' }
                      ].map((topic, i) => (
                        <div key={i} className="space-y-2">
                          <div className="flex items-center justify-between text-sm">
                            <span className="font-medium">{topic.name}</span>
                            <span className="text-gray-600">{topic.count} 次</span>
                          </div>
                          <div className="w-full bg-gray-200 rounded-full h-2">
                            <div
                              className={`${topic.color} h-2 rounded-full transition-all`}
                              style={{ width: `${(topic.count / 1234) * 100}%` }}
                            />
                          </div>
                        </div>
                      ))}
                    </div>
                  </CardContent>
                </Card>
              </motion.div>

              {/* 年级分布 */}
              <motion.div
                initial={{ opacity: 0, x: -20 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{ delay: 0.4 }}
              >
                <Card className="glassmorphism">
                  <CardHeader>
                    <CardTitle>年级分布</CardTitle>
                    <CardDescription>用户年级统计</CardDescription>
                  </CardHeader>
                  <CardContent>
                    <div className="h-64 flex items-center justify-center text-gray-500">
                      <div className="text-center">
                        <Users className="w-16 h-16 mx-auto mb-4 text-gray-400" />
                        <p>饼图功能开发中...</p>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </motion.div>

              {/* 正确率趋势 */}
              <motion.div
                initial={{ opacity: 0, x: 20 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{ delay: 0.5 }}
              >
                <Card className="glassmorphism">
                  <CardHeader>
                    <CardTitle>正确率趋势</CardTitle>
                    <CardDescription>平均答题正确率变化</CardDescription>
                  </CardHeader>
                  <CardContent>
                    <div className="h-64 flex items-center justify-center text-gray-500">
                      <div className="text-center">
                        <TrendingUp className="w-16 h-16 mx-auto mb-4 text-gray-400" />
                        <p>折线图功能开发中...</p>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </motion.div>
            </div>
          </>
        )}
      </div>
    </div>
  )
}

